<template>
  <div class="app-container">
    <!-- 操作 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" @submit.prevent>
      <el-form-item prop="ip" v-if="props.tableOperate">
        <el-input
          v-model="queryParams.ip"
          placeholder="请输入IP"
          Query
          clearable
          style="width: 240px"
          @keyup.enter="searchQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="Search"
          @click="searchQuery"
          v-if="props.tableOperate"
          >搜索</el-button
        >
        <el-button type="primary" plain icon="Refresh" @click="getData()"
          >刷新</el-button
        >
      </el-form-item>
      <el-form-item style="float: right">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:source:add']"
          v-if="props.tableOperate"
          >新增
        </el-button>
      </el-form-item>
    </el-form>
    <!-- <el-row :gutter="10" class="mb8 source_add_block">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:source:add']"
          >新增</el-button
        >
      </el-col>
    </el-row> -->
    <!-- 表格数据 -->
    <el-table
      v-loading="loading"
      :data="sourceList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" width="55">
        <template #default="scope">{{ scope.$index + 1 }}</template>
      </el-table-column>
      <el-table-column label="连接别名" prop="connectAlias" />
      <el-table-column label="数据库类型" prop="databaseType" />
      <el-table-column label="IP" prop="ip" />
      <el-table-column label="端口">
        <template #default="scope">
          <span :class="[scope.row.dbState == 2 ? 'scope_proc_red' : '']">{{
            scope.row.databasePort
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" prop="databaseName" />
      <el-table-column label="响应时长" prop="responseDuration" />
      <el-table-column label="状态">
        <template #default="scope">
          <span v-if="scope.row.databaseState == 1" class="scope_percent">正常</span>
          <span v-if="scope.row.databaseState == 2" class="scope_proc_red">异常</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="updateTime" width="100" />
      <el-table-column label="操作" align="center" width="170">
        <template #default="scope">
          <el-button
            @click="tableEdit(scope.row)"
            class="edit_btn"
            v-hasPermi="['system:source:edit']"
            >编辑</el-button
          >
          <el-button
            @click="tableDelete(scope.row)"
            class="delete_btn"
            v-hasPermi="['system:source:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
    />

    <!-- 添加或修改 -->
    <el-dialog :title="title" v-model="openStatus" width="500px" append-to-body>
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
        <!-- <el-form-item label="数据源别名" prop="datasourceAlias">
          <el-input
            v-model="form.datasourceAlias"
            placeholder="请输入数据源别名"
            auto-complete="off"
            @input="inputVal"
          />
        </el-form-item> -->
        <el-form-item label="数据库类型" prop="databaseType">
          <el-input v-model="form.databaseType" disabled />
        </el-form-item>
        <el-form-item label="连接别名" prop="connectAlias">
          <el-input
            v-model="form.connectAlias"
            placeholder="请输入连接别名"
            auto-complete="off"
            @input="inputVal"
          />
        </el-form-item>
        <el-form-item label="数据库密码" prop="databasePwd">
          <el-input
            type="password"
            v-model="form.databasePwd"
            placeholder="请输入数据库密码"
            maxlength="20"
            auto-complete="off"
            show-password
            @input="inputVal"
          />
        </el-form-item>
        <el-form-item label="数据库IP" prop="ip">
          <el-select
            v-model="form.ip"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option
              v-for="(item, index) in ip_list"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
          <!-- <el-input
            v-model="form.ip"
            placeholder="请输入数据库IP"
            auto-complete="off"
            @input="inputVal"
          /> -->
        </el-form-item>
        <el-form-item label="数据库端口" prop="databasePort">
          <el-input
            v-model="form.databasePort"
            placeholder="请输入数据库端口"
            auto-complete="off"
            @input="inputVal"
          />
        </el-form-item>
        <el-form-item label="数据库名称" prop="databaseName">
          <el-input
            v-model="form.databaseName"
            placeholder="请输入数据库名称"
            auto-complete="off"
            @input="inputVal"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <p class="lianjie_btn" @click="validateRow">连接测试</p>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancelForm">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  getList,
  queryList,
  updateData,
  deleteRow,
  validate,
} from "@/api/system/source";
import { onlineHost } from "@/api/injection";
import moment from "moment";

const router = useRouter();
const { proxy } = getCurrentInstance();
const loading = ref(false);
const sourceList = ref([]);
const ip_list = ref([]); //主机地址list
const ids = ref([]);
const total = ref(0);
const title = ref("");
const openStatus = ref(false);
const connectionHand = ref(false);
const connectionStatus = ref(false);
const data = reactive({
  form: [
    {
      datasourceAlias: "",
      connectAlias: "",
    },
  ],
  queryParams: {
    ip: "",
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    datasourceAlias: [
      { required: true, message: "数据源别名不能为空", trigger: "blur" },
    ],
    connectAlias: [
      { required: true, message: "连接别名不能为空", trigger: "blur" },
    ],
    databasePwd: [
      { required: true, message: "数据库密码不能为空", trigger: "blur" },
    ],
    ip: [{ required: true, message: "数据库IP不能为空", trigger: "blur" }],
    databasePort: [
      { required: true, message: "数据库端口不能为空", trigger: "blur" },
    ],
    databaseName: [
      { required: true, message: "数据库名称不能为空", trigger: "blur" },
    ],
  },
});
const { queryParams, form, rules } = toRefs(data);

//获取主机地址数据
function getOnlineHost() {
  onlineHost().then((response) => {
    ip_list.value = response.data;
  });
}

/** 查询列表数据 */
const props = defineProps({
  tableOperate: {
    type: Boolean,
    default: true,
  },
  ip: {
    type: String,
    required: true,
  },
});
watch(
  () => props.ip,
  (newVal, oldValue) => {
    queryParams.value.ip = newVal;
    getData();
  }
);
function getData() {
  loading.value = true;
  if (queryParams.value.ip) {
    queryList(queryParams.value).then((response) => {
      if (response.data.result === true) {
        sourceList.value = response.data.data;
        total.value = response.data.total;
        loading.value = false;
      }
    });
  } else {
    getList(queryParams.value).then((response) => {
      if (response.data.result === true) {
        sourceList.value = response.data.data;
        total.value = response.data.total;
        loading.value = false;
      }
    });
  }
}

/** 搜索按钮操作 */
function searchQuery() {
  queryParams.value.pageNum = 1;
  getData();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
}

//操作-编辑
function tableEdit(data) {
  reset();
  openStatus.value = true;
  title.value = "编辑数据源信息";
  form.value = data;
}

//操作-删除
function tableDelete(data) {
  proxy.$modal.confirm("是否确认删除此数据").then(function () {
    let form = {
      uuid: data.uuid,
    };
    deleteRow(form).then((response) => {
      if (response.data.result === true) {
        proxy.$modal.msgSuccess("删除成功");
        getData();
      } else {
        proxy.$message({
          type: "error",
          message: response.data.info,
        });
      }
    });
  });
}

//新增
function handleAdd() {
  reset();
  openStatus.value = true;
  title.value = "新增数据源信息";
}

//新增-确定
function submitForm() {
  proxy.$refs["roleRef"].validate((valid) => {
    if (valid) {
      if (!connectionHand.value) {
        proxy.$modal.msgError("请先操作连接测试");
        return;
      }
      if (!connectionStatus.value) {
        proxy.$modal.msgError("连接测试失败，不能提交");
        return;
      }

      updateData(form.value).then((response) => {
        if (response.data.result === "success") {
          if (form.value.id) {
            proxy.$modal.msgSuccess("修改成功");
          } else {
            proxy.$modal.msgSuccess("保存成功");
          }
        } else {
          proxy.$message({
            type: "error",
            message: response.data.info,
          });
        }
        openStatus.value = false;
        getData();
      });
    }
  });
}

//新增-取消
function cancelForm() {
  openStatus.value = false;
  reset();
}

//连接测试
function validateRow() {
  proxy.$refs["roleRef"].validate((valid) => {
    if (valid) {
      // form.value.updateTime = moment().format("YYYYMMDDHHmmss");
      validate(form.value)
        .then((response) => {
          if (response.data.result === "success") {
            connectionStatus.value = true;
            proxy.$modal.msgSuccess("连接成功");
            connectionHand.value = true;
          } else {
            proxy.$message({
              type: "error",
              message: response.data.info,
            });
          }
        })
        .catch((err) => {
          connectionStatus.value = false;
          connectionHand.value = true;
        });
    }
  });
}

//监听数据变化
function inputVal() {
  connectionStatus.value = false;
  connectionHand.value = false;
}

/** 重置新增的表单以及其他数据  */
function reset() {
  connectionHand.value = false;
  connectionStatus.value = false;
  form.value = {
    databaseType: "mysql",
    connectAlias: "",
    datasourceAlias: "",
    ip: "",
    databasePort: "",
    databaseName: "",
    databasePwd: "",
  };
  proxy.resetForm("roleRef");
  getData();
}

getOnlineHost();
getData();

setInterval(function () {
  getData();
}, 60000);
</script>

<style>
.source_add_block {
  justify-content: end;
}
.scope_percent {
  background: #409eff;
  padding: 3px 6px;
  color: #fff;
  font-size: 12px;
  border-radius: 3px;
}
.edit_btn,
.delete_btn {
  width: 60px;
  height: 32px;
  text-align: center;
  line-height: 32px;
  color: #fff;
  font-size: 14px;
  border-radius: 4px;
  border: 0;
}
.edit_btn {
  background: #ec8a18;
}
.delete_btn {
  background: #e15361;
}
.delete_btn:hover {
  background: rgba(225, 83, 97, 0.8);
  color: #fff;
}
.edit_btn:hover {
  background: rgba(236, 138, 24, 0.8);
  color: #fff;
}
.lianjie_btn {
  float: left;
  font-size: 14px;
  line-height: 32px;
  padding-left: 20px;
  color: #409eff;
  font-weight: bold;
  text-decoration: underline;
  margin: 0;
  cursor: pointer;
}
.scope_proc_red {
  font-weight: bold;
  background: #e15361;
  padding: 3px 6px;
  color: #fff;
  font-size: 12px;
  border-radius: 3px;
}
</style>
